<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 售后申请表
 *
 * @icon fa fa-circle-o
 */
class Aftersales extends Backend
{
 
	protected $relationSearch = true;
    /**
     * AfterSales模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AfterSales');
        $config = [
            'typeList' => $this->model->getTypeList(),
	        'statusList' => $this->model->getStatusList(),
	        'resultList' => $this->model->getResultList()
        ];
        
        $this->assignconfig($config);
        $this->assign($config);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax())
		{
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField'))
			{
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			$total = $this->model
				->with('user,order,ordergoods')
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with('user,order,ordergoods')
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	/**
	 * 编辑
	 */
	public function edit($ids = NULL)
	{
		$row = $this->model->with('user,order,ordergoods')->find($ids);
		$row = $this->model->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->join('order o', 'a.order_id = o.id', 'left')
			->join('orderGoods g', 'a.order_item_id = g.id', 'left')
			->join('shipping s', 'a.shipping_id = s.id', 'left')
			->join('dictionary dg', 'a.goods_status = dg.id', 'left')
			->join('dictionary dr', 'a.return_id = dr.id', 'left')
			->join('dictionary de', 'a.exchange_id = de.id', 'left')
			->where(['a.id' => $ids])
			->field('a.id, o.order_no, g.goods_name, a.type, a.amount, a.reason, a.content, a.images, a.status, from_unixtime(a.create_time) as create_time, u.username, a.result, s.name as shipping_name, a.shipping_no, dg.name as goods_status, dr.name as return_name, de.name as exchange_name')
			->find();
			
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$model = new \app\common\model\AfterSales();
				Db::startTrans();
				try {
					
					$itemModel = new \app\common\model\AfterItem();
					//判给买家
					if($params['result'] == $model::RESULT_USER) {
						$res = $model->pass($ids, $itemModel::ROLE_SYS, $params['reason']);
						if(!$res) {
							throw new Exception($model->getError());
						}
					} else {
						//送给卖家
						//更改状态为完成
						$params['status'] = $model::STATUS_FINISH;
						$result = $row->allowField(true)->save($params);
						
						if (!$result) {
							throw new Exception('更改售后状态出错');
						}
						
						$itemRes = $itemModel->addItem($ids, $itemModel::ROLE_SYS,'系统处理完成','系统处理完成:'.$params['reason']);
						if(!$itemRes) {
							throw new Exception('添加详情出错');
						}
					}
					
					
					
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 拒绝申请
	 */
	public function deny($ids = NULL)
	{
		$row = $this->model->where(['id' => $ids])->find();
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds))
		{
			if (!in_array($row[$this->dataLimitField], $adminIds))
			{
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					$result = $this->model->where(['id' => $ids])->update([
						'status' => \app\common\model\AfterSales::STATUS_BUS_DISAGREE,
						'update_time' => time()
					]);
					if ($result === false)
					{
						$this->error($row->getError());
					} else {
						$itemModel = new \app\common\model\AfterItem();
						$itemRes = $itemModel->addItem($ids, $itemModel::ROLE_BUS,'卖家拒绝申请','拒绝理由:'.$params['reason']);
						if($itemRes) {
							$this->success();
						} else {
							$this->error('添加售后详情出错');
						}
					}
					
					
				}
				catch (\think\exception\PDOException $e)
				{
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 同意申请
	 */
	public function pass($ids = NULL)
	{
		$row = $this->model->where(['id' => $ids])->find();
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds))
		{
			if (!in_array($row[$this->dataLimitField], $adminIds))
			{
				$this->error(__('You have no permission'));
			}
		}
		
		$model = new \app\common\model\AfterSales();
		
		$res = $model->pass($ids, \app\common\model\AfterItem::ROLE_BUS,'');
		if($res) {
			$this->success();
		} else {
			$this->error($model->getError());
		}
	}
}
